package com.rinlink.spock.demo.service

import com.rinlink.spock.demo.common.ErrorCodes
import com.rinlink.spock.demo.repository.OrderRepository
import com.rinlink.spock.demo.service.model.CreateOrderInDTO
import spock.lang.Specification

class OrderServiceSpec extends Specification {

    def "创建订单测试"(){
        given:
        def orderService = Spy(OrderService){
            userService >> Mock(UserService){
                exists(_) >> userExists
                getBalance(_) >> balance
            }
            goodsService >> Mock(GoodsService){
                exists(_) >> goodsExists
                getPrice(_) >> price
            }
            orderRepository >> Mock(OrderRepository)
        }

        when:
        CreateOrderInDTO inDto = new CreateOrderInDTO()
                .setUserId("xxxxx")
                .setGoodsId("bbbbbb")
        orderService.create(inDto)
        then:
        1 * orderService.getOrderRepository().insert({
            it.userId == "xxxxx"
            it.goodsId == "bbbbbb"
        })
        where:
        userExists|goodsExists|price|balance|errorCode
        true|true|100|100|null
    }

    def "创建订单 #testName"(){
        given:
        def orderService = Spy(OrderService){
            //Mock UserService
            getUserService() >> Mock(UserService){
                exists(_) >> userExists
                getBalance(_) >> balance
            }
            getGoodsService() >> Mock(GoodsService){
                exists(_) >> goodsExists
                getPrice(_) >> price
            }
            getOrderRepository() >> Mock(OrderRepository)
        }

        when:
        CreateOrderInDTO inDto = new CreateOrderInDTO()
                .setUserId("xxxxx")
                .setGoodsId("bbbbbb")
        orderService.create(inDto)
        then:
        def exp = thrown(IllegalArgumentException)
        exp.message == errorCode.name()
        where:
        userExists|goodsExists|price|balance|errorCode|testName
        false|null|null|null| ErrorCodes.USER_NOT_EXISTS|"用户不存在"
        true|false|_|_| ErrorCodes.GOODS_NOT_EXISTS|"商品不存在"
        true|true|100|99| ErrorCodes.BALANCE_NOT_ENOUGH| "余额不足"
    }

}